package com.diyunapp.xilinapp.me;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.PayResult;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/23.
 * 充值支付界面
 */
public class ChargePayCommitActivity extends StatusBarFragmentActivity implements View.OnClickListener {

    @Bind(R.id.paycommit_goback_ib)
    ImageButton paycommitGobackIb;
    @Bind(R.id.zhfb_pay_rb)
    RadioButton zhfbPayRb;
    @Bind(R.id.weixin_pay_rb)
    RadioButton weixinPayRb;
    @Bind(R.id.online_paytype_rg)
    RadioGroup onlinePaytypeRg;
    @Bind(R.id.paydo_commit_bt)
    TextView paydoCommitBt;
    @Bind(R.id.actionbar_status_bar)
    View actionbarStatusBar;

    private String account;
    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";
    private int paytypeflag = 1;
    private String orderInfo;
    private static final int SDK_PAY_FLAG = 1;
    private static final String WX_APP_ID = "wx3d34176dc151d20a";
    private IWXAPI wxApi;
    private ProgressDialog mProgressDialog;

private View headView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_commit1_layout);
        ButterKnife.bind(this);
         headView = findViewById(R.id.paycommit_menubar_inc);
        super.MenuWidget(headView);
        loginKey = MainActivity.myLogin.getLoginkey();
        account = getIntent().getStringExtra("account");
//        actionbarStatusBar.setVisibility(View.GONE);
//        weixinPayRb.setVisibility(View.GONE);
        initViews();

    }

    private void initViews() {
        paycommitGobackIb.setOnClickListener(this);
        paydoCommitBt.setOnClickListener(this);
        paydoCommitBt.setOnClickListener(this);
        onlinePaytypeRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.zhfb_pay_rb) {
                    paytypeflag = 1;
                } else if (checkedId == R.id.weixin_pay_rb) {
                    paytypeflag = 2;
                }
            }
        });

        zhfbPayRb.setChecked(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.paycommit_goback_ib:
                finish();
                break;
            case R.id.paydo_commit_bt:
                if (paytypeflag == 1) {
                    justDoAliPay();
                } else {
                    justWeiXinPay();
                }
                break;
            default:
                break;
        }
    }
    //------begin----------微信支付相关功能部分----------------
    private void justWeiXinPay() {
        //微信实例化
        wxApi = WXAPIFactory.createWXAPI(this, WX_APP_ID, true);
        wxApi.registerApp(WX_APP_ID);

        String url = "http://www.xilingou.com/mobile/index.php?act=wxpay&op=wx_recharge";
        RequestParams params = new RequestParams();
        params.addBodyParameter("member_id", MainActivity.myLogin.getMemberid());
        params.addBodyParameter("amount", account);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String  result =responseInfo.result;
                        Log.i("zhangxiaoxidebug","result="+result);
                        try {
                            JSONObject object = new JSONObject(result);
                            PayReq req = new PayReq();
                            req.appId			= object.getString("appid");
                            req.partnerId		= object.getString("partnerid");
                            req.prepayId		= object.getString("prepayid");
                            req.nonceStr		= object.getString("noncestr");
                            req.timeStamp		= object.getString("timestamp");
                            req.packageValue	= object.getString("package");
                            req.sign			= object.getString("sign");
                            //req.extData			= "app data"; // optional
                            //Toast.makeText(CashActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
                            //Log.e("info", "req.appId="+req.appId);
                            //Log.e("info", "req.partnerId="+req.partnerId);
                            //Log.e("info", "req.prepayId="+req.prepayId);
                            //Log.e("info", "req.nonceStr="+req.nonceStr);
                            //Log.e("info", "req.timeStamp="+req.timeStamp);
                            //Log.e("info", "req.packageValue="+req.packageValue);
                            //Log.e("info", "req.sign="+req.sign);
                            //Log.e("info", "req.extData="+req.extData);
                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            //regToWx();
                            wxApi.sendReq(req);
                            cancelProgressDialog();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onStart() {
                        buildProgressDialog("正在获取微信支付订单，请稍后...");
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        cancelProgressDialog();
                        Toast.makeText(getApplicationContext(),"微信支付订单获取失败，请联系客服处理！",Toast.LENGTH_LONG).show();
                    }
                }
        );
    }
    public void buildProgressDialog(String message) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
        }
        mProgressDialog.setMessage(message);
        mProgressDialog.setCancelable(false);
        try {
            mProgressDialog.show();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public void setProgressDialog(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.setMessage(message);
            mProgressDialog.setCancelable(true);
        }
    }
    public void cancelProgressDialog() {
        if ((mProgressDialog != null) && !isFinishing()) {
            mProgressDialog.dismiss();
        }
    }

    //------end----------微信支付相关功能部分----------------


    private void justDoAliPay() {
        String url = ""+MainActivity.url+"act=member_payment&op=recharge";
//        String url="http://xilin.diyunkeji.com/mobile/index.php?act=member_payment" +
//                "&op=recharge&member_id="+MainActivity.myLogin.getMemberid()+"&amount=1";
        RequestParams params = new RequestParams();
//        params.addBodyParameter("key", MainActivity.myLogin.getLoginkey());
        params.addBodyParameter("member_id", MainActivity.myLogin.getMemberid());
        params.addBodyParameter("amount", "account");

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "支付签名信息获取失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                                return;
                            }
                            orderInfo = jsObjectCode.getString("data");
                            requstAlipay();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "支付签名信息获取失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    Log.i("zhangxiaoxidebug", "resultInfo=" + resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(getApplicationContext(), "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void requstAlipay() {
        // 必须异步调用
        Log.i("zhangxiaoxidebug", "orderInfo = " + orderInfo);
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    Runnable payRunnable = new Runnable() {
        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(ChargePayCommitActivity.this);
            // 调用支付接口，获取支付结果
            String result = alipay.pay(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

}
